<?php

namespace Common\Behavior;

use Think\Behavior;
use Think\Hook;
use Common\Service\AddonService;

/**
 * 加载系统插件
 * Class AddonsBehavior
 * @package Common\Behavior
 */
class AddonsBehavior extends Behavior
{
    public function run(&$params)
    {
        $_list = $this->getHookList();
        foreach ($_list as $item) {
            foreach ($item['hook_list'] as $key=>$hook) {
                if(is_array($hook)) {
                    // 队列模式
                    foreach ($hook as $v) {
                        Hook::add($key, $item['classname']);
                    }
                }else if(is_numeric($key)) {
                    // 原型模式
                    Hook::add($hook, $item['classname']);
                }else if(is_string($key)){
                    // 别名模式
                    Hook::add($key, $item['classname']);
                }
            }
        }
        return true;
    }

    public function getHookList($status = 1)
    {
        $map = array(
            'status' => $status,
        );
        $result = M('Addon')->where($map)->field('name,hook_list')->select();
        $hook_list = array();
        foreach ($result as &$row) {
            $class = 'Addons\\' . $row['name'] . '\\' . $row['name'] . C('ADDON_BASE_EXT');
            $hook_list[] = array('hook_list' => unserialize($row['hook_list']), 'classname' => $class);
        }
        return $hook_list;
    }
}